package com.silverhaze.diamond.client.ui.dialogs;

import com.silverhaze.commons.ui.layout.SpringUtilities;
import com.silverhaze.commons.ui.simpledatepicker.SimpleDatePicker;
import com.silverhaze.commons.helpers.CommonUIHelper;
import com.silverhaze.diamond.client.common.AuroraConstants;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.common.entity.BrokenDetail;
import com.silverhaze.diamond.common.entity.CountedDetail;
import com.silverhaze.diamond.common.entity.Service;
import com.silverhaze.diamond.common.entity.UsedDetail;
import com.silverhaze.diamond.client.ui.UIHelper;
import com.silverhaze.diamond.client.ui.UIStringConstants;
import com.silverhaze.diamond.client.ui.table.CountedDetailTable;
import com.silverhaze.diamond.client.ui.table.model.CountedDetailsTableModel;
import com.silverhaze.diamond.client.utils.db.ServiceDataSource;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * Created by Ivan Babanin (12:02:07 01.06.2008)
 * This part of code is strictly confidential.
 * © Magnificent Software Inc.
 */
public class CompleteServiceDialog extends AbstractDialog {

    private JRadioButton guarantyRadioButton;
    private JRadioButton payedRadioButton;
    private JRadioButton modernRadioButton;
    private JRadioButton refuseRadioButton;
    private JButton installedDetailsBtn;
    private JButton assumedDetailsBtn;
    private JTable selectedInstalledDetailsList;
    private JTable selectedAssumedDetailsList;
    private SimpleDatePicker serviceCompleteDate;
    private JTextField cost;

    private Service service;
    private java.util.List<CountedDetail> usedDetailList;
    private java.util.List<CountedDetail> brokenDetailList;


    public CompleteServiceDialog(Service service) {
        super(UIHelper.getMainFrame(), "Завершение сервиса", true);

        this.service = service;

        initView();
    }

    private void initView() {
        JPanel panel = new JPanel(new SpringLayout());
        setTitle("Завершение сервиса");

        guarantyRadioButton = new JRadioButton(AuroraConstants.GUARANTY);
        payedRadioButton = new JRadioButton(AuroraConstants.PAYED);
        modernRadioButton = new JRadioButton(AuroraConstants.MODERNIZATION);
        refuseRadioButton = new JRadioButton(AuroraConstants.REFUSE);

        guarantyRadioButton.setSelected(true);

        CommonUIHelper.createButtonGroup(guarantyRadioButton,
                payedRadioButton,
                modernRadioButton,
                refuseRadioButton
        );

        final CountedDetailsTableModel installedDetailModel = new CountedDetailsTableModel(service.getUsedDetailes());
        selectedInstalledDetailsList = new CountedDetailTable(installedDetailModel);
        installedDetailsBtn = new JButton("Выбрать детали");

        final CountedDetailsTableModel brokenDetailModel = new CountedDetailsTableModel(service.getBrokenDetailes());
        selectedAssumedDetailsList = new CountedDetailTable(brokenDetailModel);

        usedDetailList = new ArrayList<CountedDetail>();
        installedDetailsBtn = new JButton(new AbstractAction("Выбрать детали") {
            public void actionPerformed(ActionEvent e) {
                DetailSelectorDialog.selectDetails(new DialogConnector() {
                    public void objectSelected(Object o) {
                        if (o != null) {
                            usedDetailList = (java.util.List<CountedDetail>) o;
                            installedDetailModel.fillData(usedDetailList);
                        }
                    }
                }, installedDetailModel.getDataList(), UsedDetail.class);
            }
        });

        brokenDetailList = new ArrayList<CountedDetail>();
        assumedDetailsBtn = new JButton(new AbstractAction("Выбрать детали") {
            public void actionPerformed(ActionEvent e) {
                DetailSelectorDialog.selectDetails(new DialogConnector() {
                    public void objectSelected(Object o) {
                        if (o != null) {
                            brokenDetailList = (java.util.List<CountedDetail>) o;
                            brokenDetailModel.fillData(brokenDetailList);
                        }
                    }
                }, brokenDetailModel.getDataList(), BrokenDetail.class);
            }
        });

        serviceCompleteDate = new SimpleDatePicker();
        cost = new JTextField(10);

        final JScrollPane installedScrollPane = new JScrollPane(selectedInstalledDetailsList);
        installedScrollPane.setPreferredSize(new Dimension(200, 200));

        final JScrollPane assumedScrollPane = new JScrollPane(selectedAssumedDetailsList);
        assumedScrollPane.setPreferredSize(new Dimension(200, 200));

        CommonUIHelper.addToPanel(panel,
                "Тип сервиса:", CommonUIHelper.createHorizontalBox(guarantyRadioButton, 31, payedRadioButton),
                "", CommonUIHelper.createHorizontalBox(modernRadioButton, refuseRadioButton),
                "Установленные детали: ", installedScrollPane,
                "", installedDetailsBtn,
                "Принятые детали: ", assumedScrollPane,
                "", assumedDetailsBtn,
                "Дата: ", serviceCompleteDate,
                "Стоимость: ", cost
        );

        SpringUtilities.makeCompactGrid(panel, 8, 2, 10, 10, 10, 10);
        panel.setBorder(BorderFactory.createTitledBorder(" Завершение сервиса "));

        JPanel result = CommonUIHelper.packInPanel(panel);
        result.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 0));

        add(result, BorderLayout.CENTER);

        add(initializeOkCancelPanel(DialogType.EDIT), BorderLayout.PAGE_END);
        setPreferredSize(new Dimension(400, 600));
        pack();

        setLocationRelativeTo(null);
    }

    protected void okPressed() {
        if (check()) {
            final HashSet<BrokenDetail> brokenDetails = new HashSet<BrokenDetail>(convertToBroken(brokenDetailList));
            final HashSet<UsedDetail> usedDetails = new HashSet<UsedDetail>(convertToUsed(usedDetailList));

//            service.setUsedDetailes(usedDetails);
//            service.setBrokenDetailes(brokenDetails);

            service.setServiceComplete(true);
            service.setServiceCompleteDate(serviceCompleteDate.getDate());

            defineServiceType(service);

            DAOLocator.getInstance().addEntities(brokenDetails);
            DAOLocator.getInstance().addEntities(usedDetails);

            service.setBrokenDetailes(brokenDetails);
            service.setUsedDetailes(usedDetails);

            DAOLocator.getInstance().update(service);
            ServiceDataSource.getInstance().updateService(service);

            dispose();
        } else {
            Dialogs.showErrorDialog(null, UIStringConstants.PLEASE_FILL_FIELDS);
        }
    }

    private void defineServiceType(Service service) {
        String serviceType = "";

        if (guarantyRadioButton.isSelected()) {
            serviceType = AuroraConstants.GUARANTY;
        } else if (payedRadioButton.isSelected()) {
            serviceType = AuroraConstants.PAYED;
        } else if (refuseRadioButton.isSelected()) {
            serviceType = AuroraConstants.REFUSE;
        } else if (modernRadioButton.isSelected()) {
            serviceType = AuroraConstants.MODERNIZATION;
        }

        service.setServiceType(serviceType);
    }

    private Collection<? extends UsedDetail> convertToUsed(List<CountedDetail> usedDetailList) {
        List<UsedDetail> usedDetails = new ArrayList<UsedDetail>(usedDetailList.size());

        for (CountedDetail countedDetail : usedDetailList) {
            UsedDetail usedDetail = new UsedDetail();
            usedDetail.setDetail(countedDetail.getDetail());
            usedDetail.setQuantity(countedDetail.getQuantity());
            usedDetails.add(usedDetail);
        }

        return usedDetails;
    }

    private Collection<? extends BrokenDetail> convertToBroken(List<CountedDetail> brokenDetailList) {
        List<BrokenDetail> brokenDetails = new ArrayList<BrokenDetail>(usedDetailList.size());

        for (CountedDetail bDetail : brokenDetailList) {
            BrokenDetail usedDetail = new BrokenDetail();
            usedDetail.setDetail(bDetail.getDetail());
            usedDetail.setQuantity(bDetail.getQuantity());
            brokenDetails.add(usedDetail);
        }

        return brokenDetails;
    }

    private boolean check() {
        try {
            final double costValue = Double.parseDouble(cost.getText().trim());
            service.setCost(costValue);
            return true;
        } catch (NumberFormatException nE) {
            return false;
        }
    }

    public static void completeService(Service service) {
        CompleteServiceDialog completeServiceDialog = new CompleteServiceDialog(service);
        completeServiceDialog.setVisible(true);
    }
}

